const mongoose = require('mongoose');
require('dotenv').config();

const connectDB = async () => {
  try {
    // 检查是否有用户名和密码环境变量
    let mongoUri = process.env.MONGODB_URI;
    
    if (process.env.MONGO_USERNAME && process.env.MONGO_PASSWORD) {
      // 如果提供了用户名和密码，则构造带认证的连接字符串
      const uriParts = process.env.MONGODB_URI.split('://');
      if (uriParts.length === 2) {
        mongoUri = `${uriParts[0]}://${process.env.MONGO_USERNAME}:${process.env.MONGO_PASSWORD}@${uriParts[1]}`;
      }
    }
    
    const conn = await mongoose.connect(mongoUri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log(`MongoDB Connected: ${conn.connection.host}`);
  } catch (error) {
    console.error(`Error: ${error.message}`);
    process.exit(1);
  }
};

module.exports = connectDB;